let shelves_arr = []

define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'outhouse/checkvouch/index' + location.search,
                    add_url: 'outhouse/checkvouch/add',
                    edit_url: 'outhouse/checkvouch/edit',
                    del_url: 'outhouse/checkvouch/del',
                    multi_url: 'outhouse/checkvouch/multi',
                    import_url: 'outhouse/checkvouch/import',
                    custom_url:'outhouse/checkvouch/getCheckList',
                    table: 'checkvouch'
                }
            });
            Fast.config.openArea = ['100%','100%'];
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                    //    {field: 'id', title: __('Id')},
                        {field: 'code_date', title: __('Code_date'), operate: 'LIKE'},
                        {field: 'code', title:__('Code'), operate: 'LIKE'},
                        {field: 'book_date', title:__('Book_date'), operate: 'LIKE'},
                        {field: 'warehouse_id', title:__('Warehouse_id'), operate: 'LIKE',formatter:function(val,row,i){
                            //return row.ware_house.name;
                        }},
                        {field: 'type', title:__('Type'),searchList: typeArr,formatter: Table.api.formatter.normal},
                        {field: 'status', title: __('Status'), searchList: {"0":'关闭',"1":'开启',"2":'完成'}, formatter:function(varl,row,i){
                                if(row.status==1){
                                    return '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="" data-field="status" data-value="1" data-original-title="点击搜索 开启"><span class="text-success">开启</span></a>';
                                }else if(row.status==2){
                                    return '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="" data-field="status" data-value="2" data-original-title="点击搜索 完成"><span class="text-primary">完成</span></a>';
                                }else{
                                    return '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="" data-field="status" data-value="0" data-original-title="点击搜索 关闭"><span class="text-primary">关闭</span></a>';
                                }
                        }},
                        {field: 'pda', title:__('Pda'), searchList:pdaFlagArr,operate: 'LIKE'},
                        {field: 'remark', title:__('Remark'), operate: 'LIKE'},
                        //{field: 'result', title:__('Result'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        //{field: 'ckstatus', title:__('Ckstatus'), visibled: false},
                        {field: 'process_text', title:__('Process'), operate: false}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            $('#deal-btn').click(function(){
                let allids =  Controller.api.selectedid(table);
                var selections = table.bootstrapTable('getSelections'); 
                if(allids.length==0) {
                	Toastr.error("请选择数据");
                	return 
                }
                
                for(let i=0;i<selections.length;i++){
                	if(selections[i].ckstatus!=0){
                		Toastr.error("存在已处理单据，请核实");
                    	return 
                	}
                }
                
                let index = layer.confirm('确定要处理盘点单据，此操作不可逆转？', {
              	  btn: ['确定','关闭'], //按钮
              	  title:'温馨提示'
              }, function(index){
                    layer.close(index);
                    let ids = Table.api.selectedids(table);
                     
                    //隐藏审核按钮，免得再次点击，重复提交
                    //$("#bdeal-btn").addClass('hidden')
                    Fast.api.ajax({
                        url: 'inventory/temporary/setting',
                        data: {id:allids}
	                      }, function (data) {
	                    	  $("a.btn-refresh").trigger("click");
	                      },function (data) {
	                    	  $("a.btn-refresh").trigger("click");
	                      });
	                });
            })
            
        },
        add: function () {
        	$(document).on("change", "#type", function(){
        	    //变更后的回调事件
        		console.log($('#type').val())
        	});

        	$('#shelves_name').on('itemRemoved', function(event) {
    		  // 在标签关闭时执行的操作
    		  console.log('标签已关闭: ' + event.item);
    		  let new_shelves_id_arr = []
    		  shelves_arr = $.grep(shelves_arr,function(obj) {
    			  if(obj.name!=event.item){
    				  new_shelves_id_arr.push(obj.id)
    			  }
    			  return obj.name!=event.item;
    		  })
    		  $("#shelves_id").val(new_shelves_id_arr)
    		});
        	
            Controller.api.bindevent();
        },
        getCheckList:function (){
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
           setTimeout(function () {
       			$(".datetimepicker_top").datetimepicker({
                    showTodayButton: true,
                    showClose: true
                });
           }, 500);
           setInterval(function(){
        	   $("#input_id_0").trigger("change");
           },500)
        },
        api: {
            bindevent: function () {
                //Form.api.bindevent($("form[role=form]"));
            	Form.api.bindevent($("form[role=form]"),function(data,ret){
            		Toastr.success("操作成功");
            		$("a.btn-refresh").click()
            		if(ret.msg=='edit'){
            			//编辑页，不返回
            			return false;
            		}
            	},function(data,ret){
            		Toastr.error(ret.msg);
            		return false;
            	});
            },
          //获取选中的行
            selectedid: function (table, current) {
                var options = table.bootstrapTable('getOptions');
                //如果有设置翻页记忆模式
                if (!current && options.maintainSelected) {
                    return options.selectedIds;
                }
                return $.map(table.bootstrapTable('getSelections'), function (row) {
                    return row[options.pk];
                });
            },
        }
    };
    return Controller;
});
/*$('#choose-goods').on('click',function(){
    var warehouse_id = $("#c-warehouse_id").val();
    top.Fast.api.open('inventory/kc/choose?warehouse_id='+warehouse_id,'选择物料',{offset: 'r',callback:function(value){
            //console.log(value);
            $("#c-basic-textarea").val(JSON.stringify(value));
            $("#free-programme-item-table").trigger("fa.event.refreshfieldlist");
        }});
})*/
function selectshelves(obj){
    let house_id = $("#c-warehouse_id").val();
    let this_obj = $(obj);
    let this_id_obj = this_obj.siblings('.c-shelves_id');
    let this_name_obj = this_obj.siblings('.c-shelves_name');
    top.Fast.api.open('information/shelves/choose?single=0&warehouse_id='+house_id,'选择货架',{offset: 'r',callback:function(value){
            // $("#c-shelves_id").val(value);
            /*this_id_obj.attr('value',value.id);
            this_name_obj.val(value.name);
            this_name_obj.selectPageRefresh();*/
    	
    		let shelves_name_arr = []
    		let shelves_id_arr = []
    		shelves_arr = []
    		$.map(value, function(obj) {
    			shelves_name_arr.push(obj.name)
    			shelves_id_arr.push(obj.id)
    			shelves_arr.push({'id':obj.id,"name":obj.name})
    		});
    		$("#shelves_id").val(shelves_id_arr)
    		$("#shelves_name").val(shelves_name_arr.join('|'))
    		
    		let tagsInput = $('#shelves_name').data('tagsinput');
    		tagsInput.destroy();
    		$('#shelves_name').tagsinput();
    		
    		if(!value.length){
        		Backend.api.toastr.error('请先选择货架、库区');
                return false;
        	}
    	
    }});
}

function chooseGoods(id){
	let house_id = $("#c-warehouse_id").val();
    if(!house_id){
        Backend.api.toastr.error('请先选择仓库');
        return false;
    }
    
    top.Fast.api.open('information/Inventory/choosebyclass','选择物料',{offset: 'r',callback:function(value){
    	if(!value.length){
    		$("#"+id).val('')
    		return;
    	}
    	$("#"+id).val(value[0].number)
    	if($("#inv_number_start").val()!=''&&$("#inv_number_end").val()!=''){
    		if($("#inv_number_end").val()<$("#inv_number_start").val()){
    			$("#inv_number_end").val('')
    			Backend.api.toastr.error('结束编码不能小于开始编码');
    	        return false;
    		}
    	}
    }});
}

function toDeleteCkItem(index){
	let ids = parseInt($("#input_id_"+index).val());
	if(ids==''){
		Toastr.error('参数ID错误');
		return 
	}
	
	let lay_index = layer.confirm('确定要删除该盘点记录？', {
	  btn: ['确定','关闭'], //按钮，
	  title:'温馨提示'
	  }, function(){
		  Fast.api.ajax({
              url: 'outhouse/checkvouch/delitem',
              data: {"ids":ids}
          }, function (data,ret) {
        	  if(ret.code == 1){
        		  $("#tr_"+index).remove();
        		  Toastr.success('删除成功');
        	  }else{
        		  Toastr.error('删除失败');
        	  }
        	  return false;
          },function(){});
		  layer.close(lay_index);
		  return false
	},function(){
		layer.close(lay_index);
	});
}

function aa(){
	alert()
}
